{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b88a2df3-5990-4796-8c93-053cff5c8c89",
   "metadata": {},
   "source": [
    "## 1、如何把一个多页的paf文件拆分为多个单独的pdf文件？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "825b38ca-2acd-4e98-9f78-90485174063e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Retrieving notices: ...working... done\n",
      "Channels:\n",
      " - conda-forge\n",
      " - defaults\n",
      "Platform: linux-64\n",
      "Collecting package metadata (repodata.json): done\n",
      "Solving environment: done\n",
      "\n",
      "# All requested packages already installed.\n",
      "\n",
      "\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "conda install -c conda-forge pypdf2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85df1e54-e77e-4112-b7e7-2994331633e8",
   "metadata": {},
   "source": [
    "### 第一版本：可以正确的文件拆分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "88a27d69-c483-4f78-b898-78682671e6d0",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "执行完毕~\n"
     ]
    }
   ],
   "source": [
    "\n",
    "from PyPDF2 import PdfReader, PdfWriter\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "def split_pdf(input_pdf, output_folder):\n",
    "    \"\"\"\n",
    "    将 PDF 文件拆分为单独的页面，并将它们保存在指定的输出文件夹中。\n",
    "\n",
    "    Args:\n",
    "        input_pdf (str): 输入 PDF 文件的路径。\n",
    "        output_folder (str): 输出文件夹的路径。\n",
    "    \"\"\"\n",
    "    \n",
    "    # 创建输出文件夹（如果不存在）\n",
    "    if not os.path.exists(output_folder):\n",
    "        os.makedirs(output_folder)\n",
    "\n",
    "    with open(input_pdf, \"rb\") as f:\n",
    "        reader = PdfReader(f)\n",
    "\n",
    "        for i in range(len(reader.pages)):\n",
    "            writer = PdfWriter()\n",
    "            writer.add_page(reader.pages[i])\n",
    "            with open(f\"{output_folder}/page_{i+1}.pdf\", \"wb\") as outfile:\n",
    "                writer.write(outfile)\n",
    "    print('执行完毕~')\n",
    "\n",
    "def delete_folder_contents(folder_path):\n",
    "    \"\"\"\n",
    "    删除指定文件夹中的所有文件和子文件夹。\n",
    "\n",
    "    Args:\n",
    "        folder_path (str): 要清空的文件夹的路径。\n",
    "    \"\"\"\n",
    "    for filename in os.listdir(folder_path):\n",
    "        file_path = os.path.join(folder_path, filename)\n",
    "        try:\n",
    "            if os.path.isfile(file_path) or os.path.islink(file_path):\n",
    "                os.unlink(file_path)\n",
    "            elif os.path.isdir(file_path):\n",
    "                shutil.rmtree(file_path)\n",
    "        except Exception as e:\n",
    "            print(f\"删除 {file_path} 失败： {e}\")\n",
    "\n",
    "# 示例用法\n",
    "input_pdf = \"ex.pdf\"\n",
    "output_folder = \"split_pdfs\"\n",
    "\n",
    "# 清空输出文件夹\n",
    "delete_folder_contents(output_folder)\n",
    "\n",
    "# 拆分 PDF 文件\n",
    "split_pdf(input_pdf, output_folder)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "908fdd55-1f32-4588-bad9-ec3e98219bc0",
   "metadata": {},
   "source": [
    "### 第二版本：可以按照要来给每个文件命名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bff6a0c1-930d-4e84-a53a-a5ee449b3ef7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "目录 split_pdfs 为空，跳过删除。\n",
      "执行完毕~\n"
     ]
    }
   ],
   "source": [
    "from PyPDF2 import PdfReader, PdfWriter\n",
    "import os\n",
    "import shutil\n",
    "import re\n",
    "\n",
    "def extract_info_and_rename(pdf_path):\n",
    "    \"\"\"\n",
    "    从 PDF 内容中提取信息并重命名文件。\n",
    "\n",
    "    Args:\n",
    "        pdf_path (str): PDF 文件的路径。\n",
    "    \"\"\"\n",
    "    with open(pdf_path, \"rb\") as f:\n",
    "        reader = PdfReader(f)\n",
    "        page = reader.pages[0]\n",
    "        text = page.extract_text()\n",
    "\n",
    "        # 提取奖项名\n",
    "        match = re.search(r\"荣获(.{3})\", text)\n",
    "        if match:\n",
    "            award_name = match.group(1)\n",
    "        else:\n",
    "            award_name = \"未知奖项\"\n",
    "\n",
    "        # 提取证书编号\n",
    "        match = re.search(r\"No:\\d{4}[A-Z]{4}\\d{3}[A-Z]\\d{3}\", text)\n",
    "        if match:\n",
    "            cert_number = match.group(0)\n",
    "            cert_number = cert_number.replace(\":\", \".\")  # 删除冒号\n",
    "        else:\n",
    "            cert_number = \"未知编号\"\n",
    "\n",
    "        # 提取获奖人名 (修正)\n",
    "        lines = text.split(\"\\n\")\n",
    "        for i, line in enumerate(lines):\n",
    "            if line.startswith(\"你们团队\"):\n",
    "                winner_name = lines[i-1].strip()  # 获奖人名在“你们团队”前一行\n",
    "                winner_name = winner_name.replace(\":\", \"\")  # 删除冒号\n",
    "                break\n",
    "        else:\n",
    "            winner_name = \"未知获奖人\"\n",
    "\n",
    "        # 构建新文件名\n",
    "        new_filename = f\"{award_name}_{cert_number}_{winner_name}.pdf\"\n",
    "\n",
    "        # 重命名文件\n",
    "        os.rename(pdf_path, os.path.join(os.path.dirname(pdf_path), new_filename))\n",
    "\n",
    "def split_pdf(input_pdf, output_folder):\n",
    "    \"\"\"\n",
    "    将 PDF 文件拆分为单独的页面，并将它们保存在指定的输出文件夹中。\n",
    "\n",
    "    Args:\n",
    "        input_pdf (str): 输入 PDF 文件的路径。\n",
    "        output_folder (str): 输出文件夹的路径。\n",
    "    \"\"\"\n",
    "\n",
    "    # 创建输出文件夹（如果不存在）\n",
    "    if not os.path.exists(output_folder):\n",
    "        os.makedirs(output_folder)\n",
    "\n",
    "    with open(input_pdf, \"rb\") as f:\n",
    "        reader = PdfReader(f)\n",
    "\n",
    "        for i in range(len(reader.pages)):\n",
    "            writer = PdfWriter()\n",
    "            writer.add_page(reader.pages[i])\n",
    "            with open(f\"{output_folder}/page_{i+1}.pdf\", \"wb\") as outfile:\n",
    "                writer.write(outfile)\n",
    "            # 提取信息并重命名文件\n",
    "            extract_info_and_rename(f\"{output_folder}/page_{i+1}.pdf\")\n",
    "\n",
    "    print('执行完毕~')\n",
    "    \n",
    "\n",
    "def delete_folder_contents(folder_path):\n",
    "    \"\"\"\n",
    "    删除指定文件夹中的所有文件和子文件夹。\n",
    "\n",
    "    Args:\n",
    "        folder_path (str): 要清空的文件夹的路径。\n",
    "    \"\"\"\n",
    "    # 判断输出文件夹（如果不存在）\n",
    "    if not os.path.exists(folder_path):\n",
    "        print(f\"目录 {folder_path} 不存在，跳过删除。\")\n",
    "        return\n",
    "        \n",
    "    # 判断输出文件夹中是否有文件\n",
    "    if not os.listdir(folder_path):  # 检查目录是否为空\n",
    "        print(f\"目录 {folder_path} 为空，跳过删除。\")\n",
    "        return\n",
    "        \n",
    "    # 删除输出文件夹中的文件\n",
    "    for filename in os.listdir(folder_path):\n",
    "        file_path = os.path.join(folder_path, filename)\n",
    "        try:\n",
    "            if os.path.isfile(file_path) or os.path.islink(file_path):\n",
    "                os.unlink(file_path)\n",
    "            elif os.path.isdir(file_path):\n",
    "                shutil.rmtree(file_path)\n",
    "        except Exception as e:\n",
    "            print(f\"删除 {file_path} 失败： {e}\")\n",
    "\n",
    "# 示例用法\n",
    "input_pdf = \"ex.pdf\"\n",
    "output_folder = \"split_pdfs\"\n",
    "\n",
    "# 清空输出文件夹\n",
    "delete_folder_contents(output_folder)\n",
    "\n",
    "# 拆分 PDF 文件\n",
    "split_pdf(input_pdf, output_folder)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66794f14-7809-436b-b863-430ea4c2a601",
   "metadata": {},
   "source": [
    "## 3、批量给多个邮箱发送邮件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e78d9231-823f-48ea-be25-f68af571dc48",
   "metadata": {},
   "outputs": [],
   "source": [
    "conda install -c conda-forge yagmail"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e58d2986-3e82-49a7-a5aa-95aa6ec35365",
   "metadata": {},
   "outputs": [],
   "source": [
    "import smtplib\n",
    "from email.mime.text import MIMEText\n",
    "from email.utils import formataddr\n",
    "import traceback\n",
    "import threading\n",
    " \n",
    " \n",
    "# 发件人邮箱账号\n",
    "sender = 'zhangkai@openatom.org'\n",
    "# user登录邮箱的用户名，password登录邮箱的密码（授权码，即客户端密码，非网页版登录密码），但用腾讯邮箱的登录密码也能登录成功\n",
    "password = 'AkxLnzLFQfXzXEJ3'\n",
    " \n",
    "baidu_url = 'https://www.baidu.com'\n",
    " \n",
    " \n",
    "def send_mail(mail_to, subject, content, sub_type='plain'):\n",
    " \n",
    "    ret = True\n",
    "    try:\n",
    "        # 邮件内容\n",
    "        msg = MIMEText(content, sub_type, 'utf-8')\n",
    "        # 括号里的对应发件人邮箱昵称、发件人邮箱账号\n",
    "        msg['From'] = formataddr([sender, sender])\n",
    "        # 括号里的对应收件人邮箱昵称、收件人邮箱账号\n",
    "        msg['To'] = formataddr([mail_to, mail_to])\n",
    "        # 邮件的主题\n",
    "        msg['Subject'] = subject\n",
    "        print(\"1111\")\n",
    " \n",
    "        # SMTP服务器，腾讯企业邮箱端口是465，腾讯邮箱支持SSL(不强制)， 不支持TLS\n",
    "        # qq邮箱smtp服务器地址:smtp.qq.com,端口号：456\n",
    "        # 163邮箱smtp服务器地址：smtp.163.com，端口号：25\n",
    "        server = smtplib.SMTP_SSL(\"smtp.exmail.qq.com\", 465)\n",
    "        # 登录服务器，括号中对应的是发件人邮箱账号、邮箱密码\n",
    "        print(\"2222\")\n",
    "        server.login(sender, password)\n",
    "        print(1111)\n",
    "        # 发送邮件，括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件\n",
    "        result = server.sendmail(sender, [mail_to, ], msg.as_string())\n",
    "        print(result)\n",
    "        if not result:\n",
    "            print(\"邮件发送成功！\")\n",
    "        else:\n",
    "            print(\"以下邮件发送失败：\", result)\n",
    "            \n",
    "        # 关闭连接\n",
    "        server.quit()\n",
    "        # 如果 try 中的语句没有执行，则会执行下面的 ret=False\n",
    "    except Exception :\n",
    "        traceback.format_exc()\n",
    "        ret = False\n",
    "    return ret\n",
    " \n",
    " \n",
    "def send_async_mail(mail_to, subject, content, sub_type='plain'):\n",
    "    thr = threading.Thread(target=send_mail, args=[mail_to, subject, content, sub_type])\n",
    "    thr.start()\n",
    " \n",
    " \n",
    "def send_async_mail_prepare(user_name, user_password, user_email):\n",
    "    email_title = f'邮件主题-xxxxxx！'\n",
    "    content = f\"尊敬的xxxxxx您好：<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;\" \\\n",
    "              f\"这里是邮件的内容 xxxxxx， <br/><br/>\" \\\n",
    "              f\"&nbsp;&nbsp;&nbsp;&nbsp;百度地址是：<a href='{baidu_url}'>Baidu</a>\"\n",
    "    send_async_mail(user_email, email_title, content, \"html\")\n",
    " \n",
    " \n",
    "# if __name__ == \"__main__\":\n",
    "send_async_mail_prepare('test', 'test', 'succpeking@foxmail.com')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}